package com.core.controller;

import com.core.domain.DTO.GlhStadiumInfoDTO;
import com.core.domain.DTO.LoginUserInfoDTO;
import com.core.domain.DTO.LygStadiumDTO;
import com.core.domain.DTO.StadiumDTO;
import com.core.domain.Stadium;
import com.core.domain.User;
import com.core.domain.useStadium;
import com.core.service.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 刘玉贵
 * @version 666
 */

@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = {"http://localhost:8080", "http://localhost:63343"})
public class AdminController {
    @Autowired
    private GlhService glhService;
    @Autowired
    private DjsService djsService;

    @Resource
    private TmhService tmhService;

    @Resource
    private PylService pylService;

    @Resource
    private LygService lygService;

    @GetMapping("/getAllUserInf")
    public List<User> getAllUserInf(HttpServletRequest request, HttpServletResponse response){
        return tmhService.getListUsers();
    }

//    获取数据库中所有的场馆名字
    @GetMapping("/getStadiumNames")
    @ResponseBody
    public List<String> queryStadiumName(){
        System.out.println("getStadiumNames拜访问了");
        List<String> names = pylService.queryStadiumName();
        return names;
    }

    @RequestMapping("/quaryStdiumStatus")
    public void quaryStdiumStatus(HttpServletRequest request, HttpServletResponse response, @RequestParam("name") String name) throws ServletException, IOException {
        HashMap<useStadium, Integer> inf = new HashMap<>();
        List<useStadium> list = pylService.quaryStdiumStatus(name);
        int count = 0;
        for (useStadium usestadium : list) {
            inf.put(usestadium, count);
            count++;
            System.out.println(usestadium);
        }
        request.setAttribute("option", name);
        request.setAttribute("inf", inf);
        request.getRequestDispatcher("/reservation_page/reserveStadiumStatus.jsp").forward(request, response);
    }

    @RequestMapping("/quaryUserInfo/{userAccount}")
    public void quaryUserInfo(HttpServletRequest request, HttpServletResponse response, @PathVariable("userAccount") String userAccount) throws ServletException, IOException {
        User user = pylService.quaryUserInfo(userAccount);
        request.setAttribute("userinfo", user);
        request.setAttribute("option", userAccount);
        request.getRequestDispatcher("/reservation_page/queryUserInfo.jsp").forward(request, response);
    }

    @RequestMapping("/queryStadiumInfo")
    public void queryStadiumInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam("name") String stadiumName) throws ServletException, IOException {
        Stadium stadium = pylService.queryStadiumInfo(stadiumName);
        request.setAttribute("stadiumInfo", stadium);
        request.setAttribute("option", stadiumName);
        request.getRequestDispatcher("/reservation_page/queryStadiumInfo.jsp").forward(request, response);

    }

    @RequestMapping("/updateStadiumInfo")
    public void updateStadiumInfo(HttpServletRequest request, HttpServletResponse response) {
        Object id = request.getParameter("id");
        Object newcontent = request.getParameter("newcontent");
        Object oldcontent = request.getParameter("oldcontent");
        System.out.println(id + "  " + newcontent + "  " + oldcontent);
        int i = pylService.updateStadium(id, newcontent, oldcontent);
        System.out.println(i);

    }


    /**
     * 下载所有用户信息
     *
     * @return 用户信息.csv
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/DownLoadAllUsers")
    public ResponseEntity<byte[]> getAllUsers() throws UnsupportedEncodingException {
        // 从数据库或其他地方获取数据列表
        List<User> listUsers = tmhService.getListUsers();
        // 将数据列表转化为 CSV 格式的字符串
        String csvString = tmhService.convertToCsvUsers(listUsers);

        // 设置响应头信息，告诉浏览器该文件需要被下载
        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", "user.csv");

        // 将 CSV 字符串转化为字节数组，并构建 ResponseEntity 对象
        return new ResponseEntity<>(csvString.getBytes("GBK"), headers, HttpStatus.OK);
    }

    @PostMapping("/addStadium")
    public int addStadium(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonString = request.getReader().readLine();
        System.out.println(jsonString);
        // 使用Jackson将JSON对象字符串转换为Java对象
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println("“11111");
        GlhStadiumInfoDTO userTmp = objectMapper.readValue(jsonString, GlhStadiumInfoDTO.class);
        System.out.println(userTmp);
        glhService.addStadium(userTmp);
        return 1;
    }

    /**
     * 获取所有user
     * @param request
     * @param response
     * @throws IOException
     */
    @PostMapping("/getUsers")
    public void getAllUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        List<User> users = glhService.selectAllUsers();

        //2. 转为JSON
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(users);
        //3. 写数据
        System.out.println(users);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
    @PostMapping("deleteByAccount")
    public int deleteByAccount(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonString = request.getReader().readLine();
        System.out.println(jsonString);
        // 使用Jackson将JSON对象字符串转换为Java对象
        ObjectMapper objectMapper = new ObjectMapper();
        LoginUserInfoDTO userTmp = objectMapper.readValue(jsonString, LoginUserInfoDTO.class);
        //System.out.println(userTmp);
        System.out.println(userTmp.getUserAccount());
        String account = userTmp.getUserAccount();
        glhService.deleteByAccount(account);
        return 1;
    }
    @PostMapping("/deleteByStadiumName")
    public int deleteByStadiumName(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String jsonString = request.getReader().readLine();
        System.out.println(jsonString);
        // 使用Jackson将JSON对象字符串转换为Java对象
        ObjectMapper objectMapper = new ObjectMapper();
        GlhStadiumInfoDTO userTmp = objectMapper.readValue(jsonString, GlhStadiumInfoDTO.class);
        System.out.println(userTmp.getStadiumName());
        return glhService.deleteByStadiumName(userTmp.getStadiumName());
    }


    @PostMapping("/getTimeMoney")
    public Map<String, Integer> getTimeMoney(@RequestParam("startTime") String startTimeStr,
                                             @RequestParam("endTime") String endTimeStr) {
        Map<String, Integer> map = djsService.finalMoney(startTimeStr, endTimeStr);
        return map;
    }


    @PostMapping("/getUserNumbers")
    public Map<String, Integer> getUserNumbers(@RequestParam("startTime") String startTimeStr,
                                               @RequestParam("endTime") String endTimeStr) {
        Map<String, Integer> eachTeamUserNumbers = djsService.getUserNumbers(startTimeStr, endTimeStr);
        return eachTeamUserNumbers;
    }


    @PostMapping("/getUtilizationRate")
    public Map<String, String> getUtilizationRate(@RequestParam("startTime") String startTimeStr,
                                                  @RequestParam("endTime") String endTimeStr) {
        Map<String, String> eachTeamUserUtilizationRate = djsService.getUtilizationRate(startTimeStr, endTimeStr);
        return eachTeamUserUtilizationRate;
    }

    @PostMapping("getPopular")
    public List<Map<String, Object>> getPopular(@RequestParam("startTime") String startTimeStr,
                                                @RequestParam("endTime") String endTimeStr) {
        List<Map<String, Object>> eachTeamPopular = djsService.getPopular(startTimeStr, endTimeStr);
        return eachTeamPopular;
    }

    @PostMapping("getAge")
    public List<Map<String, Object>> getAge(@RequestParam("startTime") String startTimeStr,
                                            @RequestParam("endTime") String endTimeStr) {
        List<Map<String, Object>> eachTeamAgePopular = djsService.getAge(startTimeStr, endTimeStr);
        return eachTeamAgePopular;
    }
}
